package com.EE7th.service.impl;

import com.EE7th.Result.PageResult;
import com.EE7th.dao.StudentDao;
import com.EE7th.domain.Student;
import com.EE7th.dto.PageQueryDTO;
import com.EE7th.dto.StudentDTO;
import com.EE7th.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao studentDao;

    @Override
    @Transactional
    public void insertStudent(Student student) {
        studentDao.insertStudent(student);
    }

    @Override
    public PageResult pageQuery(PageQueryDTO dto) {
        // 如果 dto == null 或者 page/pageSize 未设置，则返回全部数据
        if (dto == null || dto.getPage() == null || dto.getPageSize() == null
                || dto.getPage() <= 0 || dto.getPageSize() <= 0) {
            List<StudentDTO> allStudents = studentDao.pageQuery();
            return new PageResult(allStudents.size(), allStudents);
        }
        // 正常分页流程
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<StudentDTO> students = studentDao.pageQuery();
        PageInfo<StudentDTO> pageInfo = new PageInfo<>(students);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public Student getById(int studentId) {
        return studentDao.getById(studentId);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        for(Integer id : ids){
            studentDao.deleteStudent(id);
        }
    }


    @Override
    public void updateStudent(Student student) {
        studentDao.updateStudent(student);
    }
}